var net = require("net");
var chatServer = net.createServer();
var clientMap = new Object();

var i = 0;//连接名称的流水号
chatServer.on("connecttion",(client) => {
  console.log("客户端有人连入")
  clent.name = ++i;
  clentMap[client.name] = client;
  
  //对客户端发送消息的监听
  client.on("data", (data) => {
    console.log("客户端传来"+data);
    broadcast(data,client);
  })
  
  //数据错误事件的处理
  client.on("error", (err) => {
    console.log(err);
    client.end();
  })
  
  
  //客户端关闭
  client.on("close", (data) => {
    delete clientMap[client.name]
    console.log(client.name + "下线了")
    broadcast(client.name + "下线了,client)
  })
})


//消息广播
function broadcast(message,client){
  for(var key in clientMap){
    clientMap[key].write(client.name +" say:" +message)
  }
}

chatServer.listen(9000)